package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.responseClasses.StoryView;
import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

/**
 * Servlet implementation class NewestStories
 */
public class MostRecentStories extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MostRecentStories() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * Gets the top 5 most recent story fragments in the system. A list of {@link com.storyroad.responseClasses.StoryView}
	 * instances which contain information about the story fragments is returned to the front-end. 
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		ArrayList<StoryView> mostRecentStories = new ArrayList<StoryView>();
		String f_requestType = request.getParameter("request_type");
		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
		}
		PrintWriter out = response.getWriter();
		Connection conn = new DBConnection().connect();
		PreparedStatement stmt = null;
		String title;
		String tags;
		int s_id;
		double avgRating;

		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				// Get 5 of the most recent story fragments 
				stmt = conn.prepareStatement("SELECT Story.s_id,title,(totalRating / ratingCount) AS avgRating FROM "
								+ TableNames.STORIES_TABLE + " ORDER BY date DESC LIMIT 5");
				ResultSet rs = stmt.executeQuery();
				request.setCharacterEncoding("utf8");
				response.setContentType("application/json");

				while (rs.next()) {
					s_id = rs.getInt("s_id");
					title = rs.getString("title");
					avgRating = rs.getDouble("avgRating");
					tags = Utilities.getTags(conn, s_id);
					// Create StoryView instances and add them to the list
					mostRecentStories.add(new StoryView(s_id, title, tags, avgRating));
				}

				if (f_requestType.equals("Android")) {
					JSONObject mostRecentStoriesJsonObject = new JSONObject();
					try {
						mostRecentStoriesJsonObject.put("mostRecentStories",
								mostRecentStories);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.print(mostRecentStoriesJsonObject.toString());
				} else if (f_requestType.equals("Web")) {
					request.setAttribute("mostRecentStories", mostRecentStories);
					/*
					 * After the operation is completed, redirect to HighestRatedStories servlet to gather further
					 * content for the main page
					 */
					request.getRequestDispatcher("HighestRatedStories").forward(request, response);
				} else {
					// DO NOTHING!
				}
			} catch (SQLException e) {
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
